/**
 * Created by Feng on 2016/3/25.
 */
import {provide, Directive, forwardRef,Input} from '@angular/core';
import {Control,NG_VALIDATORS,Validator} from '@angular/common';
import {Observable} from 'rxjs/Observable';
/* beautify ignore:end */

@Directive({
    selector: '[async-unique]',
    providers: [provide(NG_VALIDATORS, {useExisting: AsyncUniqueValidator, multi: true})],
    inputs: ['params: async-params', 'url: async-url']
})

export class AsyncUniqueValidator implements Validator {
    constructor(
    ) {}
    params: any;
    url: string;

    validate(c: Control): {[key: string]: any} {
        let errorKey: string = 'asyncUnique';
        let value = c.value;
        console.log(c);
        console.log(c.errors);
        if ( value == null ) { return null; }
        if ( c.errors && c.errors[errorKey]) {return null;}

        return new Promise(resolve  => {
            //this._global.get(this.url, this.params).catch(error => {
            //
            //    console.log('catch');
            //    resolve({errorKey: false});
            //    return Observable.throw('服务器错误1');
            //}).subscribe(data => {
            //    console.log('subscribe');
            //    resolve({errorKey: true});
            //});
        });
    }
}